import * as request from '../constant/fetch-request'
import HTTP_CODE from '../constant/http-code'
import {REFRESH_PUBLISHERS} from '../constant/action-type'
import {message} from 'antd'

const refreshPublishers = data => ({
  type: REFRESH_PUBLISHERS,
  data
})

export const getPublishers = () => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/publishers`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(refreshPublishers(res.body))
      }
    })()
  }
}
export const getUserByNameOrEmail = (userNameOrEmail) => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/publishers/${userNameOrEmail}`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(refreshPublishers(res.body))
      }
    })()
  }
}

export const addPublisher = (publisherId, userNameOrEmail) => {
  return (dispatch) => {
    (async () => {
      const res = await request.post(`./api/publishers`, publisherId)
      if (res.status === HTTP_CODE.CREATED) {
        message.success('添加成功')
        dispatch(getUserByNameOrEmail(userNameOrEmail))
      }
    })()
  }
}

export const deletePublisher = (id, userNameOrEmail) => {
  return dispatch => {
    (async () => {
      const res = await request.del(`./api/publishers/${id}`)
      if (res.status === HTTP_CODE.NO_CONTENT) {
        message.success('移除成功')
        dispatch(getUserByNameOrEmail(userNameOrEmail))
      }
    })()
  }
}
